package com.toolmanrln.logistics.modules.user.service.impl;

import com.toolmanrln.logistics.modules.permission.entity.Permission;
import com.toolmanrln.logistics.modules.permission.service.IPermissionService;
import com.toolmanrln.logistics.modules.user.entity.User;
import com.toolmanrln.logistics.modules.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ToolMan.RLN
 * @since 2020/5/16 12:23
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        User user = userService.getByAccount(account);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (user != null) {
            // 获取用户授权
            List<Permission> tbPermissions = permissionService.findByUserId(user.getId());
            // 声明用户授权
            tbPermissions.forEach(tbPermission -> {
                if (tbPermission != null && tbPermission.getPowerName() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getPowerName());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
            return new org.springframework.security.core.userdetails.User(user.getAccount(), user.getPassword(), grantedAuthorities);
        }
        throw new UsernameNotFoundException("用户名或者密码输入错误，请重新输入!");
    }
}
